<?php
/**
 * 数据库操作类
 */

class DB
{
	// DB服务器
	private $host = "";
	// DB端口
	private $port = "";
	// DB数据库名
	private $dbname = "";
	// DB用户名
	private $user = "";
	// DB密码
	private $password = "";
	// DB链接
	public $db_link;
	// 结果集
	public $result;
	// 调试模式
	private $debug;
	/**
	 * 构造函数
	 */
	public function __construct(){
		$dbConfig = [
			'host' => '192.168.157.1',
			'port' => '1433',
			'dbname' => 'text',
			'username' => 'sa',
			'password' => 'root'
		];
		$this->host = $dbConfig['host'];
		$this->port = $dbConfig['port'];
		$this->dbname = $dbConfig['dbname'];
		$this->user = $dbConfig['username'];
		$this->password = $dbConfig['password'];
		$this->debug = true;
		$this->connect();
	}

	/**
	 * 连接DB
 	 */
	public function connect(){
		//DB已连接时
		if($this->db_link) {
			return;
		}
		else {
			$this->db_link = odbc_pconnect("Driver={SQL Server};Server=".$this->host.";Database=".$this->dbname, $this->user, $this->password);
			if($this->debug && !$this->db_link){
				var_dump(odbc_errormsg());
				exit;
			}
		}
	}

	/**
	 * 关闭DB连接
	 */
	public function close(){
		if ($this->db_link) {
			if(!odbc_close($this->db_link)){
				
			}
		}
	}

	/**
	 * 运行sql
	 * @param  $sql
	 * @return $this->result
	 */
	public function query($sql){
		//清空结果集
		if ($this->result) {
			unset($this->result);
		}
		//运行sql
		$this->result = odbc_exec($this->db_link,$sql);
		if($this->debug && !$this->result){
			var_dump(odbc_errormsg());
			exit;
		}
		return $this->result;
	}

	/**
	 * 取得sql运行结果的第一条
	 * @param  $sql
	 * @return $this->rows
	 */
	public function getOneRow($sql) {
		if ($this->rows) {
			unset($this->rows);
		}
		$this->query($sql);
		if(is_resource($this->result)){
			$this->rows = odbc_fetch_array($this->result);
		}else{
			$this->rows = array();
		}
		return $this->rows;
	}

	/**
	 * 取得sql运行结果
	 * @param  $sql
	 * @return $this->myrow
	 */
	public function getAll($sql) {
		$this->query($sql);
		$rows = array();
		if(is_resource($this->result)){
			while ($row=odbc_fetch_array($this->result)) {
				$rows[] = $row;
			}
		}
		return $rows;
	}
	/**
	 * sql转义(防注入)
	 * @param $str            unescaped_string
	 * @param $escapedStr     escaped_string
	 */
	public function escape($str)
	{
		return str_replace("'","''",$str);
	}
}
?>